const {executeQuery} = require('../config/db_config')
const express = require('express')

let couponRouter = express.Router()
couponRouter.use(express.json())


/**
 * 获取券详情
 */
couponRouter.get("/id",async (req,resp)=>{
  const user_id = req.query.id
  const sql = `select * from coupons where  id=${user_id}`
 const res = await executeQuery(sql)
 resp.send({
   code:200,
   msg:'success',
   data:res[0]
 })
})


/**
 * 获取指定用户的所有券
 */
couponRouter.get("/user",async (req,resp)=>{
  const user_id = req.query.id
  const sql = `select coupons.*,coupon_user.num from coupon_user,coupons 
  where coupon_user.user_id=${user_id} and coupon_user.coupon_id=coupons.id`
 const res = await executeQuery(sql)
 resp.send({
   code:200,
   msg:'success',
   data:res
 })
})
/**
 * 删除指定用户的优惠券
 */
couponRouter.delete("/",async (req,resp)=>{
  const id = req.query.id
  const sql = `delete from coupon_user where id=${id}`
 const res = await executeQuery(sql)
 resp.send({
   code:200,
   msg:'success',
   data:res
 })
})

/**
 * 获取所有用户的券
 */
couponRouter.get("/list",async (req,resp)=>{
  const limit = req.query.limit
  const startIndex = (req.query.now_page-1)*limit
  const sql = `select coupons.*,coupon_user.num,user.username
   from coupon_user,coupons,user 
   where coupon_user.user_id=user.id and coupon_user.coupon_id=coupons.id limit ${startIndex},${limit}`
  const sql1 = `select count(*) as num
   from coupon_user,coupons,user 
   where coupon_user.user_id=user.id and coupon_user.coupon_id=coupons.id`
  const res = await executeQuery(sql)
  const res1 = await executeQuery(sql1)
  resp.send({
    code:200,
    msg:"success",
    data:{
      total:res1[0]?.num,
      list:res
    }
  })
})


module.exports={
  couponRouter
}